<template>
  <div class="menu-container">
    <a-menu
      v-model:open-keys="openKeys"
      v-model:selected-keys="selectedKeys"
      mode="inline"
      theme="light"
      class="diy-menu"
      style="height: 100%; overflow: auto; margin-top: -1px"
      @click="clickMenuItem"
    >
      <template v-for="item in menus" :key="item.name">
        <menu-item :menu-info="item" />
      </template>
    </a-menu>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, computed, toRefs, watch } from 'vue';
import { Menu } from 'ant-design-vue';
import MenuItem from './menu-item.vue';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from '@/store';
import { routes } from '@/router';

export default defineComponent({
  name: 'Menu',
  components: {
    MenuItem,
    'a-sub-menu': Menu.SubMenu,
    'a-menu-item': Menu.Item
  },
  setup() {
    // 当前路由
    const currentRoute = useRoute();
    const router = useRouter();
    const route = useRoute();
    const store = useStore();

    watch(
      () => route.fullPath,
      () => {
        state.openKeys = getOpenKeys();
        state.selectedKeys = getSelectKeys();
      }
    );

    // 获取当前打开的子菜单
    const getOpenKeys = () =>
      currentRoute.matched[1]?.meta.openKey
        ? [currentRoute.matched[1]?.meta.openKey]
        : [currentRoute.matched[1]?.name];
    const getSelectKeys = () =>
      currentRoute.meta.openName ? [currentRoute.meta.openName] : [currentRoute.name];

    const state = reactive({
      openKeys: getOpenKeys(),
      selectedKeys: getSelectKeys()
    });

    const menus = computed(
      () =>
        store.getters['asyncRoute/menus'] ?? routes.find((item) => item.name == 'Layout')!.children
    );

    // 点击菜单
    const clickMenuItem = ({ key }) => {
      if (/http(s)?:/.test(key)) {
        window.open(key);
      } else {
        router.push({ name: key });
      }
    };

    return {
      ...toRefs(state),
      menus,
      clickMenuItem
    };
  }
});
</script>

<style lang="less" scoped>
.menu-container {
  width: 100%;
  height: calc(~'100% - 12px');
  margin-top: 12px;
  .logo {
    width: 100%;
    height: 60px;
    display: flex;
    align-items: center;
    box-sizing: border-box;
    justify-content: flex-start;
    padding-left: 20px;
    box-sizing: border-box;
    border-bottom: 1px solid rgba(255, 255, 255, 0.2);
    img {
      width: 58px;
      height: 25px;
    }
  }
}

.diy-menu::-webkit-scrollbar {
  width: 0 !important;
}
</style>
